/*
 * @Author       : huangzb
 * @Date         : 2024-01-25 20:01:08
 * @LastEditors: guangyunl
 * @LastEditTime: 2024-04-03 13:58:53
 * @Description  : 商品管理
 * @FilePath     : \Interface\app\service\s_products.js
 */
"use strict";
const Service = require("egg").Service;
const { Op } = require("sequelize");

const { failRes, successRes } = require("../extend/helper");
const { Journal } = require("../exception/Journal");
const Classes = require("../model/Classes");

function toInt(str) {
  if (typeof str === "number") return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class sProducts extends Service {
  // pc
  // 查
  async pc_s_query(params) {
    // console.log('paramsProducts:===============> ', params);
    let response = null;
    const { ctx } = this;

    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);

      let where = {
        title: {
          [Op.like]: `%${params?.title ?? ""}%`, // 使用 Op.like 实现模糊匹配
        },
        decs: {
          [Op.like]: `%${params?.decs ?? ""}%`, // 使用 Op.like 实现模糊匹配
        }
      };
      const count = await ctx.model.Products.count({ where });
      const result = await ctx.model.Products.findAndCountAll({
        where,
        include: [
          // 关联查询商品分类表
          {
            model: ctx.model.Classes,
            attributes: ["id", "title"],
            through: { attributes: [] }, // 隐藏 products_classes 联结表
          },
        ],
        order: [["id", "ASC"]], // 排序
        attributes: [
          "id",
          "title",
          "decs",
          "defaultImg",
          "sort",
          "price",
          "inventory",
          "createdAt",
          "updatedAt",
        ],
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });

      await Journal(ctx, { operatorType: "商品信息 -> 查询", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: count || 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 商品信息查询");
      await Journal(ctx, { operatorType: "商品信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 增
  async pc_s_create(params) {
    let response = null;
    const { ctx } = this;
    let transaction;
    try {
      // 建立事务对象
      transaction = await ctx.model.transaction();
      const productResult = await ctx.model.Products.create(
        params,
        { transaction },
        {
          attributes: {
            extends: ["id", "title", "price", "decs", "defaultImg", "sort", "inventory"],
          },
        } // 向数据库插入特定字段
      );
      params?.classesTitle?.forEach(async _item => {
        const classes_result = await ctx.model.Classes.findOne(
          { where: { id: _item || "" } },
          { transaction }
        );
        if (classes_result) {
          // 添加新的分类关联
          await classes_result.setProducts(productResult);
        }
      });
      await transaction.commit();
      await Journal(ctx, { operatorType: "商品信息 -> 新增", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 商品信息新增");
      await transaction.rollback();
      await Journal(ctx, { operatorType: "商品信息 -> 新增", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 改
  async pc_s_update(params) {
    console.log("params: ", params);
    let response = null;
    let transaction;
    const { ctx } = this;
    try {
      // 建立事务对象
      transaction = await ctx.model.transaction();
      // 更新商品
      await ctx.model.Products.update(
        params,
        {
          where: { id: params.id },
        },
        { transaction }
      );
      const product_result = await ctx.model.Products.findOne({
        where: { id: params?.id ?? "" },
        transaction,
      });
      const classes_result = await ctx.model.Classes.findAll(
        {
          where: {
            id: { [Op.in]: params?.classesTitle ?? [] },
          },
        },
        { transaction }
      );
      if (classes_result) {
        // 添加新的分类关联
        await product_result.setClasses(classes_result);
      }
      await transaction.commit();
      await Journal(ctx, { operatorType: "商品信息 -> 编辑", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 商品信息编辑");
      await transaction.rollback();
      await Journal(ctx, { operatorType: "商品信息 -> 编辑", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 删
  async pc_s_delete(params) {
    let response = null;
    try {
      const { ctx } = this;
      await ctx.model.Products.destroy({
        where: { id: params.id },
      });
      await Journal(ctx, { operatorType: "商品信息 -> 删除", code: 200 });
      response = successRes();
    } catch (error) {
      console.error(error, "<---- error - 商品信息删除");
      await Journal(ctx, { operatorType: "商品信息 -> 删除", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 详情
  async wa_s_detail(params) {
    let response = null;
    const { ctx } = this;
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);

      const product = await ctx.model.Products.findByPk(params.id);
      console.log("product: ", product);
      if (!product) {
        throw 401;
      }
      // const result = await ctx.model.Product.sgetResourcesAndCount(params.id, {
      //   offset: (currentPage - 1) * pageSize,
      //   limit: pageSize,
      //   where: {
      //     name: {
      //       [Op.like]: `%${params?.name ?? ""}%`, // 使用 Op.like 实现模糊匹配
      //     },
      //   },
      // });
      // console.log("result: ", result);
      await Journal(ctx, { operatorType: "商品信息 -> 详情", code: 200 });
      response = successRes(product);
    } catch (error) {
      console.error(error, "<---- error - 商品信息详情");
      await Journal(ctx, { operatorType: "商品信息 -> 详情", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 批量挂载文件资源
  //   async pc_s_batchMount (params) {
  //     console.log('params: ', params);
  //     let response = null;
  //     const { ctx } = this;
  //     try {
  //       // 1. 查询特定的产品
  //       const product = await ctx.model.Product.findByPk(params?.id);
  //       console.log('product: ', product);

  //       if (!product) {
  //         throw (401);
  //       }
  //       // 2. 查询要添加的资源
  //       const resourcesToAdd = await ctx.model.Resource.findAll({
  //         where: {
  //           id: (params?.resourceIds ?? []),
  //         },
  //       });
  //       console.log('resourcesToAdd: ', resourcesToAdd);
  //       // 3. 将资源添加到产品
  //       const createdAt = new Date();
  //       const updatedAt = new Date();
  //       await product.addResources(
  //         resourcesToAdd,
  //         {
  //           through: { createdAt, updatedAt },
  //         });
  //       await Journal(ctx, { operatorType: '商品信息 -> 批量挂载资源', code: 200 });
  //       response = successRes(200);
  //     } catch (error) {
  //       console.error(error, '<---- error - 商品信息批量挂载资源');
  //       await Journal(ctx, { operatorType: '商品信息 -> 批量挂载资源', code: 401 });
  //       response = failRes(401);
  //     }
  //     return response;
  //   }

  // 删除商品资源
  //   async pc_s_deleteMountProduct (params) {
  //     console.log('params: ', params);
  //     let response = null;
  //     const { ctx } = this;
  //     try {
  //       const product = await ctx.model.Product.findByPk(params?.id);
  //       if (!product) {
  //         throw (401);
  //       }
  //       const resourcesToAdd = await ctx.model.Resource.findAll({
  //         where: {
  //           id: (params?.resourceIds ?? []),
  //         },
  //       });
  //       console.log('resourcesToAdd: ', resourcesToAdd);
  //       await product.removeResources(resourcesToAdd);
  //       await Journal(ctx, { operatorType: '商品信息 -> 删除资源', code: 200 });
  //       response = successRes(200);
  //     } catch (error) {
  //       console.error(error, '<---- error - 商品信息批量挂载资源');
  //       await Journal(ctx, { operatorType: '商品信息 -> 删除资源', code: 401 });
  //       response = failRes(401);
  //     }
  //     return response;
  //   }

  // wa
  // 查询商品信息【小程序端】
  async wa_s_query(params) {
    let response = null;
    const { ctx } = this;
    try {
      const result = await ctx.model.Product.findAll({
        where: {
          title: {
            [Op.like]: `%${params?.title ?? ""}%`,
          },
        },
      });
      await Journal(ctx, { operatorType: "商品信息 -> 查询", code: 200 });
      response = successRes(result);
    } catch (error) {
      console.error(error, "<---- error - 商品信息查询");
      await Journal(ctx, { operatorType: "商品信息 -> 查询", code: 401 });
      response = failRes(401);
    }
    return response;
  }

  // 首页商品搜索【小程序端】
  async wa_s_search_products(params) {
    console.log("params: 首页搜索", params);
    let response = null;
    const { ctx } = this;
    const title = params?.title ?? "";
    try {
      const currentPage = toInt(params?.currentPage ?? 1);
      const pageSize = toInt(params?.pageSize ?? 10);
      const count = await ctx.model.Products.count({
        where: {
          title: {
            [Op.like]: `%${title || ""}%`,
          },
        },
      });
      
      const result = await ctx.model.Products.findAndCountAll({
        where: {
          title: {
            [Op.like]: `%${title || ""}%`,
          },
        },
        include: [
          // 关联查询商品分类表
          {
            model: ctx.model.Classes,
            attributes: ["id", "title"],
            through: { attributes: [] }, // 隐藏 products_classes 联结表
          },
        ],
        order: [["sort", "DESC"]], // 排序
        limit: pageSize, // 每页多少条
        offset: pageSize * (currentPage - 1), // 跳过多少条
      });
      console.log("result: 首页搜索", result);
      await Journal(ctx, { operatorType: "首页商品搜索 -> 搜索", code: 200 });
      response = successRes({
        records: result?.rows ?? [],
        total: count || 0,
        pageSize,
        currentPage,
      });
    } catch (error) {
      console.error(error, "<---- error - 首页商品搜索");
      await Journal(ctx, { operatorType: "首页商品搜索 -> 搜索", code: 401 });
      response = failRes(401);
    }
    return response;
  }
}

module.exports = sProducts;
